package tt.love.hw.common;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import tt.love.hw.common.config.ActionBean;
import tt.love.hw.common.config.ActionConfig;
import tt.love.hw.common.config.FormBean;

public class ActionMapping {

	Logger log = LoggerFactory.getLogger(ActionMapping.class);
	private static Map<String, ActionExecutor> urlActionExecutorMapping = new HashMap<String, ActionExecutor>();
	private static Map<String, FormBean> urlActionFormMapping = new HashMap<String, FormBean>();
	private ActionConfig actionConfig;

	public ActionMapping(InputStream in) {
		init(in);
	}


	public void addUrlActionExecutorMapping(ActionExecutor actionExecutor,
			String url) {
		urlActionExecutorMapping.put(url, actionExecutor);
	}

	public void addUrlActionFormMapping(FormBean formbean, String url) {
		urlActionFormMapping.put(url, formbean);
	}

	public ActionExecutor getActionExecutor(String url) {
		ActionExecutor actionExecutor = urlActionExecutorMapping.get(url);
		if (actionExecutor == null)
			throw new ActionException("Invalid Request");
		return actionExecutor;
	}

	public FormBean getActionForm(String url) {
		ActionBean action = actionConfig.getActions().get(url);
		if (action == null)
			throw new ActionException("Invalid Request");
		return urlActionFormMapping.get(action.getForm());
	}
	
	public String getErrorPage(String url) {
		ActionBean action = actionConfig.getActions().get(url);
		if (action == null)
			throw new ActionException("Invalid Request");
		return action.getError_page();
	}


	public void init(InputStream in) throws ActionException {
		actionConfig = new ActionConfig(in);
		for (Map.Entry<String, ActionBean> action : actionConfig.getActions()
				.entrySet()) {
			addUrlActionExecutorMapping(new ActionExecutor(
					AppContextHolder.getAppcontext().getBean(action.getValue().getType()), action
							.getValue().getMethod()), action.getKey());
		}
		for (Map.Entry<String, FormBean> form : actionConfig.getForms()
				.entrySet()) {
			addUrlActionFormMapping(form.getValue(), form.getKey());
		}

	}

}
